package alt.fr.ma.np.activities;

import java.util.ArrayList;

import alt.fr.ma.np.R;
import alt.fr.ma.np.soap.Parameter;
import alt.fr.ma.np.soap.SOAPRequest;
import alt.fr.ma.np.tools.GenericTextWatcher;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class RegisterActivity extends Activity {

	private ProgressDialog progressDialog;
	private SOAPRequest soapRequest;
	private static final int PICK_IMAGE = 1;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		switch (display.getRotation()) {
		case Surface.ROTATION_0:
			setContentView(R.layout.register);
			break;
		case Surface.ROTATION_90:
			setContentView(R.layout.register_landscape);
			break;
		case Surface.ROTATION_180:
			break;
		case Surface.ROTATION_270:
			break;
		}
		
		((TextView) findViewById(R.id.REG_FirstNameField)).addTextChangedListener(new GenericTextWatcher(findViewById(R.id.REG_FirstNameError)));
		((TextView) findViewById(R.id.REG_LastNameField)).addTextChangedListener(new GenericTextWatcher(findViewById(R.id.REG_LastNameError)));
		((TextView) findViewById(R.id.REG_EmailField)).addTextChangedListener(new GenericTextWatcher(findViewById(R.id.REG_EmailError)));
		((TextView) findViewById(R.id.REG_PasswordField)).addTextChangedListener(new GenericTextWatcher(findViewById(R.id.REG_PasswordError)));
	}
	
	public void saveAction(View view) {
		switch (view.getId()) {
		case R.id.REG_Save:
			
			new AsyncTask<Integer, Integer, Boolean>() {

				@Override
				protected void onPreExecute() {
					
					String firstName = ((TextView) findViewById(R.id.REG_FirstNameField))
							.getText().toString();
					String lastName = ((TextView) findViewById(R.id.REG_LastNameField))
							.getText().toString();
					String email = ((TextView) findViewById(R.id.REG_EmailField))
							.getText().toString();
					String password = ((TextView) findViewById(R.id.REG_PasswordField))
							.getText().toString();

					boolean cancel = false;

					if (firstName.equals("")) {
						((ImageView) findViewById(R.id.REG_FirstNameError))
								.setVisibility(View.VISIBLE);
						cancel = true;
					}
					
					if (lastName.equals("")) {
						((ImageView) findViewById(R.id.REG_LastNameError))
								.setVisibility(View.VISIBLE);
						cancel = true;
					}
					
					if (email.equals("")) {
						((ImageView) findViewById(R.id.REG_EmailError))
								.setVisibility(View.VISIBLE);
						cancel = true;
					}
					
					if (password.equals("")) {
						((ImageView) findViewById(R.id.REG_PasswordError))
								.setVisibility(View.VISIBLE);
						cancel = true;
					}
					
					if (!cancel) {
					
						ArrayList<Parameter> params = new ArrayList<Parameter>();
						
						String profileInformation = "";

						profileInformation += ((EditText) findViewById(R.id.REG_FirstNameField))
								.getText() + "|";
						profileInformation += ((EditText) findViewById(R.id.REG_LastNameField))
								.getText() + "|";
						profileInformation += ((EditText) findViewById(R.id.REG_EmailField))
								.getText() + "|";
						profileInformation += ((EditText) findViewById(R.id.REG_PasswordField))
								.getText() + "|";

						params.add(new Parameter("sAction", "Register"));
						params.add(new Parameter("sParams", profileInformation));

						soapRequest = new SOAPRequest("sociablon", "WSTechnicalUser", "Sociablon01",
								"WSSociablonWebService", params);
						
						progressDialog = ProgressDialog.show(
								RegisterActivity.this, "", "Requesting registration...");						
					} else
						this.cancel(false);
				}
				
				@Override
				protected Boolean doInBackground(Integer... params) {
					
					// Starting the SOAP request and waiting for the response
					Thread request = new Thread(soapRequest);
					try {
						request.start();
						request.join();
						progressDialog.dismiss();
					} catch (InterruptedException e) {
						Log.d("ERROR - RegisterActivity", "InterruptedException",
								e);
					}

					String soapResponse = null;
					try {
						soapResponse = soapRequest.getSOAPResponse();
					} catch (Exception e) {
						Log.d("ERROR - LoginActivity",
								"SOAPResponseException: " + e.getMessage());
					}

					Log.d("NORMAL - RegisterActivity", "SOAPResponse = "
							+ soapResponse);

					return (soapResponse != null)
							&& soapResponse.charAt(0) == ('1') ? true : false;
				}
				
				@Override
				protected void onPostExecute(Boolean result) {
					
					AlertDialog alertDialog = new AlertDialog.Builder(
							RegisterActivity.this).create();
					alertDialog.setTitle("Register");
					alertDialog.setIcon(R.drawable.barrehautaddagendas);
					
					if (result)
						alertDialog
						.setMessage("Your registration was successfull!");
					else
						alertDialog.setMessage("An error occured!");
					
					alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
							finish();
						}
					});
					alertDialog.show();
				}				
			}.execute();
			break;
		}
	}
	
	public void cancelAction(View view) {
		switch (view.getId()) {
		case R.id.REG_Cancel:
			finish();
			break;
		}
	}
	
	public void pickPictureAction(View view) {
		switch (view.getId()) {
		case R.id.REG_PickPicture:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if(requestCode == PICK_IMAGE && data != null && data.getData() != null){
	        Uri uri = data.getData();

	        if (uri != null) {
	        	
//	            //User had pick an image.
//	            Cursor cursor = getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
//	            cursor.moveToFirst();
//
//	            //Link to the image
//	            final String imageFilePath = cursor.getString(0);
//	            cursor.close();
	            
	            ((ImageView) findViewById(R.id.REG_ProfileImage))
				.setImageURI(uri);
	        }
	    }
	    super.onActivityResult(requestCode, resultCode, data);
	}
}
